<template>
  <meta name="referrer" content="no-referrer">
  <div class="shop-type-analysis">
    <div class="chart">
      <a-spin :spinning="!showChart">
        <div id="myEchart" style="height: 300px;" />
      </a-spin>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { markerDataType } from '../market'
import axios from "axios";
import { provinceSuffixMap } from './region'

interface CustomOption extends echarts.EChartsCoreOption {
  visualMap: (echarts.VisualMapComponentOption & {
    inRange: {
      color: string[];
    }
  });
  series: (echarts.SeriesOption&{
    itemStyle: {
      areaColor: string;
    }
  })[];
}

const props = withDefaults(defineProps<{
  dataSource: markerDataType[]
}>(), {})

const myEchart = ref<echarts.ECharts | null>(null)
const showChart = ref(false)
const option = ref<CustomOption>({
  title: {
    text: '商家数量地域分布',
    left: 'right',
    triggerEvent: true,
  },
  tooltip: {
    trigger: 'item',
    showDelay: 0,
    transitionDuration: 0.2,
  },
  visualMap: {
    align: 'left',
    min: 0,
    max: 1000,
    inRange: {
      color: [],
    },
    text: ['高', '低'],
    calculable: true,
  },
  series: [
    {
      name: '店铺数',
      type: 'map',
      roam: true,
      map: 'china',
      zoom: 1.5,
      itemStyle: {
        areaColor: '#e0ffff',  // 默认区域颜色
      },
      // 设置地图的文字
      label: {
        show: true,
        fontSize: 10,
        color: '#434c4c',
      },
      emphasis: {
        label: {
          show: true,
        },
      },
      data: [],
    },
  ],
})
const mapData = ref()

// 颜色转换
const hexToRgb = (hex: string) => {
  let c: any;
  if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
    c = hex.substring(1).split('');
    if (c.length === 3) {
      c = [c[0], c[0], c[1], c[1], c[2], c[2]];
    }
    c = '0x' + c.join('');
    return [(c >> 16) & 255, (c >> 8) & 255, c & 255];
  }
  throw new Error('Bad Hex');
};

// 生成渐变颜色
const generateGradientColors = (startColor: string, endColor: string, steps: number) => {
  const start = hexToRgb(startColor);
  const end = hexToRgb(endColor);
  const stepFactor = 1 / (steps - 1);
  const gradientColors = [];

  for (let i = 0; i < steps; i++) {
    const r = Math.round(start[0] + (end[0] - start[0]) * stepFactor * i);
    const g = Math.round(start[1] + (end[1] - start[1]) * stepFactor * i);
    const b = Math.round(start[2] + (end[2]) * stepFactor * i);
    gradientColors.push(`rgb(${r},${g},${b})`);
  }
  return gradientColors;
};

// 获取地图数据
const setMap = async() => {
  const res = await axios.get('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
  mapData.value = res.data;
}

// 格式化省市区名称
const completeProvinceName = (shortName: string): string => {
  for (const [key, suffix] of Object.entries(provinceSuffixMap)) {
    if (shortName.startsWith(key)) {
      return key + suffix;
    }
  }
  // 如果没有匹配到，返回原始名称
  return shortName;
};

const setOptionData = async() => {
  //  设置数据
  const arr = [] as { name: string, value: number}[];
  props.dataSource.forEach((item) => {
    // 获取城市名称
    const procity = item.procity? item.procity.split(' ')[0] : '';
    const existingEntry = arr.find((entry) => entry.name === procity);
    if (existingEntry) {
      existingEntry.value++;
    } else {
      arr.push({ name: procity ? procity : '', value: 1 });
    }
  });
  arr.sort((a, b) => a.value - b.value);
  //  生成颜色示例
  const gradientColors = generateGradientColors('#e0ffff', '#006edd', arr.length +1);
  //  设置左侧柱子示例颜色
  option.value.visualMap.inRange.color = gradientColors;
  //  设置左侧柱子最小值
  option.value.visualMap.min = arr[0]?.value;
  //  设置左侧柱子最大值
  option.value.visualMap.max = arr[arr.length - 1]?.value;
  // 设置地图默认颜色
  option.value.series[0].itemStyle.areaColor = gradientColors.shift() || '';
  // 设置数据
  option.value.series[0].data = arr.map((item,index) => {
    return {
      name: completeProvinceName(item.name),
      value: item.value,
      itemStyle: {
        color: gradientColors[index]
      }
    }
  })
  // 获取地图数据
  await setMap()
  nextTick(() => {
    showChart.value = true
    myEchart.value =  markRaw(echarts.init( document.getElementById('myEchart')));
    // 加载中国地图的GeoJSON数据
    if (mapData.value) {
      echarts.registerMap('china', mapData.value);
    }
    if (myEchart.value) {
      myEchart.value.setOption(option.value, true);
      myEchart.value.resize(); // 强制重绘图表
    }
  })
};

const init = () => {
  setOptionData()
}

watch(() => props.dataSource, () => {
  init()
}, {
  deep: true,
  immediate: true,
})
</script>

<style lang="scss" scoped>

</style>